package middleware

import (
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/admin"
	"strings"

	"github.com/gin-gonic/gin"
)

type Result struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if !strings.HasPrefix(authHeader, "Bearer ") {
			c.AbortWithStatusJSON(401, Result{
				Success: false,
				Data:    "",
				Message: "Unauthorized",
			})
			return
		}

		// 提取token
		token := strings.TrimPrefix(authHeader, "Bearer ")

		var adminTokenStruct admin.AdminTokenStruct
		model.GetModelDataFirst(
			model.Db,
			adminTokenStruct.TableName(),
			&adminTokenStruct,
			model.QueryOptions{
				Conditions: map[string]interface{}{
					"access_token": token,
				},
			})

		if adminTokenStruct.Id == 0 {

			c.AbortWithStatusJSON(200, Result{
				Success: false,
				Data:    "",
				Message: "token失效",
			})
			return
		}

		c.Set("admin_id", adminTokenStruct.AdminId)

		c.Next()
	}
}
